package com.jpyl.jpMedicalTreatment.view.fragment.common;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import android.support.annotation.Nullable;
import android.view.View;

import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.example.sdkumeng.share.BHaiGouShareContent;
import com.forxindu.kit.box.JavaKit;
import com.forxindu.kit.box.PreferenceKit;
import com.forxindu.kit.box.ViewKit;
import com.jpyl.jpMedicalTreatment.MedicalApplication;
import com.jpyl.jpMedicalTreatment.R;

import com.jpyl.jpMedicalTreatment.common.MedicalSettings;
import com.jpyl.jpMedicalTreatment.model.ErrorMessageModel;
import com.jpyl.jpMedicalTreatment.model.IsSignModel;
import com.jpyl.jpMedicalTreatment.model.ResponseModel;
import com.jpyl.jpMedicalTreatment.model.RxSpf_UserModel;
import com.jpyl.jpMedicalTreatment.model.event.MineEvent;
import com.jpyl.jpMedicalTreatment.network.Const;
import com.jpyl.jpMedicalTreatment.network.Network;
import com.jpyl.jpMedicalTreatment.network.api.ApiError;
import com.jpyl.jpMedicalTreatment.network.api.RequestApi;
import com.jpyl.jpMedicalTreatment.util.CircleImageView;
import com.jpyl.jpMedicalTreatment.util.QRCodeUtil;
import com.jpyl.jpMedicalTreatment.util.StringUtil;
import com.jpyl.jpMedicalTreatment.view.activity.HomeActivity;
import com.jpyl.jpMedicalTreatment.view.activity.LoginActivity;
import com.jpyl.jpMedicalTreatment.view.activity.TestActivity;
import com.jpyl.jpMedicalTreatment.view.activity.self.AboutActivity;
import com.jpyl.jpMedicalTreatment.view.activity.self.CertificationActivity;
import com.jpyl.jpMedicalTreatment.view.activity.self.DeliveryActivity;
import com.jpyl.jpMedicalTreatment.view.activity.self.FeedbackActivity;
import com.jpyl.jpMedicalTreatment.view.activity.self.MyDiscountActivity;
import com.jpyl.jpMedicalTreatment.view.activity.self.SecurityCheckActivity;
import com.jpyl.jpMedicalTreatment.view.activity.self.UpdatePasswordActivity;
import com.jpyl.jpMedicalTreatment.view.fragment.BaseFragment;
import com.jpyl.jpMedicalTreatment.view.widget.LogOutDialog;
import com.jpyl.jpMedicalTreatment.view.widget.MineScanDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;

import butterknife.BindView;

import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


/**
 * 医生患者代理-我的
 * Created by 521546564465 on 2018/11/5.
 */

@SuppressLint("ValidFragment")
public class SelfFragment extends BaseFragment {

    @BindView(R.id.img_mine_photo)
    CircleImageView imgMinePhoto;
    @BindView(R.id.tv_mine_name)
    TextView tvMineName;
    @BindView(R.id.tv_mine_integral)
    TextView tvMineIntegral;
    final RequestApi publicApi = Network.getRequestApi();
    RxSpf_UserModel spfUserModel;
    String userId = "";


    public SelfFragment(Context context) {
        // TODO Auto-generated constructor stub
        super(context);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.self_fragment_layout;
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);

        spfUserModel = RxSpf_UserModel.create(getContext());
        userId = spfUserModel.userId().get();
        tvMineIntegral.setText(spfUserModel.point().get() + "");
        tvMineName.setText(spfUserModel.username().get() + "");
    }

    @OnClick({R.id.img_mine_scan, R.id.tv_mine_share, R.id.tv_mine_recommend, R.id
            .rela_mine_myDiscount, R.id.rela_mine_myPrize, R.id.rela_mine_toBeShipped, R.id
            .rela_mine_shipped, R.id.rela_mine_securityManagement, R.id.rela_mine_feedBack, R.id
            .rela_mine_certification, R.id.rela_mine_securityCheck, R.id.rela_mine_signOut, R.id
            .rela_mine_about})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //右上角二维码
            case R.id.img_mine_scan:
                showMineScanDialog();
                break;
            //分享
            case R.id.tv_mine_share:
                BHaiGouShareContent soaringShareContent = new BHaiGouShareContent();
                soaringShareContent.setContent("金朋医疗");
                soaringShareContent.setTitle("分享链接");
                String url = "http://www.jpylqx.com/";
                String webUrl = "";
                if (!JavaKit.isStringEmpty(webUrl)) {
                    soaringShareContent.setContentUrl(webUrl);
                } else {
                    soaringShareContent.setContentUrl(url);
                }
                soaringShareContent.setImage(BitmapFactory.decodeResource(getResources(), R
                        .drawable.img_login_logo));
                showShareWindow(soaringShareContent);
                break;
            //签到
            case R.id.tv_mine_recommend:
                jpylCheckTodaySign();
                break;
            //我的优惠
            case R.id.rela_mine_myDiscount:
                startActivity(new Intent(getActivity(), MyDiscountActivity.class).putExtra
                        ("flag", Const.MYDISCOUNT));
                break;
            //我的奖品
            case R.id.rela_mine_myPrize:
                startActivity(new Intent(getActivity(), MyDiscountActivity.class).putExtra
                        ("flag", Const.MYPRISE));
                break;
            //待发货
            case R.id.rela_mine_toBeShipped:
                startActivity(new Intent(getActivity(), DeliveryActivity.class).putExtra
                        ("flag", Const.TOSHIPPED));
                break;
            //已发货
            case R.id.rela_mine_shipped:
                startActivity(new Intent(getActivity(), DeliveryActivity.class).putExtra
                        ("flag", Const.SHIPPED));
                break;
            //安全管理（修改密码）
            case R.id.rela_mine_securityManagement:
                startActivity(new Intent(getActivity(), UpdatePasswordActivity.class));
                break;
            //反馈、申诉、举报
            case R.id.rela_mine_feedBack:
                startActivity(new Intent(getActivity(), FeedbackActivity.class));
                break;
            //实名认证
            case R.id.rela_mine_certification:
                startActivity(new Intent(getActivity(), CertificationActivity.class));
                break;
            //防伪查询
            case R.id.rela_mine_securityCheck:
                startActivity(new Intent(getActivity(), SecurityCheckActivity.class));
                break;
            //关于
            case R.id.rela_mine_about:
                startActivity(new Intent(getActivity(), AboutActivity.class));
                break;
            //退出
            case R.id.rela_mine_signOut:
                showLogOutDialog();
                break;
        }
    }

    public void showLogOutDialog() {
        LogOutDialog.Builder builder = new LogOutDialog.Builder(getActivity());
        LogOutDialog dialog = builder.setMessage("退出登录？").setTitle("").setPositiveButton("退出",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        logout();
                        dialog.dismiss();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        }).create();
        dialog.setCancelable(false);
        dialog.show();
    }

    //退出登陆
    void logout() {
        publicApi.jpylLogout(spfUserModel.loginname().get()).map(new Func1<ResponseModel<String>,
                String>() {
            @Override
            public String call(ResponseModel<String> responseModel) {
                if (responseModel.getCode() != 0) {
                    String msg = responseModel.getMsg();
                    throw new ApiError(responseModel.getCode(), msg);
                }
                return responseModel.getMsg();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                            ViewKit.showToast(getContext(), error.getMsg() + "");
                        }
                    }

                    @Override
                    public void onNext(String msg) {
                        ViewKit.showToast(getContext(), msg + "");
                        if (msg.equals("登出成功")) {
                            Intent intent = new Intent(getActivity(), LoginActivity.class);
                            startActivity(intent);
                            HomeActivity.activity.finish();
                            PreferenceKit.setSharedPreference(MedicalApplication
                                    .applicationContext, MedicalSettings.MEMBER_COOKIE, "");
                        }
                    }
                });
    }

    //检查今天是否签到
    private void jpylCheckTodaySign() {

        publicApi.jpylCheckTodaySign(userId).map(new Func1<ResponseModel<IsSignModel>,
                IsSignModel>() {
            @Override
            public IsSignModel call(ResponseModel<IsSignModel> responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<IsSignModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                            ViewKit.showToast(getContext(), error.getMsg() + "");
                        }
                    }

                    @Override
                    public void onNext(IsSignModel model) {
                        if (model.isSign()) {
                            ViewKit.showToast(getActivity(), "今日已签到，请明日再来签到");
                        } else {
                            jpylSign();
                        }
                    }
                });
    }

    //签到
    void jpylSign() {
        publicApi.jpylSign(userId).map(new Func1<ResponseModel<String>,
                String>() {
            @Override
            public String call(ResponseModel<String> responseModel) {
                if (responseModel.getCode() != 0) {
                    String msg = responseModel.getMsg();
                    throw new ApiError(responseModel.getCode(), msg);
                }
                return responseModel.getMsg();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                            ViewKit.showToast(getContext(), error.getMsg() + "");
                        }
                    }

                    @Override
                    public void onNext(String msg) {
                        ViewKit.showToast(getContext(), msg + "");
                        //签到成功，积分加1
                        if (!StringUtil.isEmpty(tvMineIntegral.getText().toString())) {
                            int point = Integer.parseInt(tvMineIntegral.getText().toString()) + 1;
                            tvMineIntegral.setText(point + "");
                        }

                    }
                });
    }

    //显示二维码Dialog
    public void showMineScanDialog() {
        String phoneNumber = spfUserModel.loginname().get();
        if (!JavaKit.isStringEmpty(phoneNumber)) {
            String message = "用户：" + phoneNumber + "。已经是会员";
            MineScanDialog.Builder builder = new MineScanDialog.Builder(getActivity());
            Bitmap myBitmap = QRCodeUtil.createQRCodeBitmap(message, 480, 480);
            MineScanDialog dialog = builder.setMessage(myBitmap).create();
            dialog.setCancelable(true);
            dialog.setCanceledOnTouchOutside(true);
            dialog.show();
        }
    }

    private void image() {
        String cookieStr = PreferenceKit.getSharedPreference(getActivity(), MedicalSettings
                .MEMBER_COOKIE, "");
        String url = "https://39.97.164.75:443/jpyl/client/attachment/photo/20181231183803605.JPG";
        GlideUrl cookie = new GlideUrl(url, new LazyHeaders.Builder().addHeader("Cookie",
                cookieStr).build());
        ImageView view = new ImageView(getActivity());
        Glide.with(this).load(cookie).into((ImageView) view);
    }

    /**
     * 实名认证后，修改姓名后更新界面
     *
     * @param obj
     */
    @Subscribe
    public void onEvent(Object obj) {
        if (obj instanceof MineEvent) {
            tvMineName.setText(((MineEvent) obj).getName());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
